package Trabajo

import groovy.grape.Grape
 
//@GrabResolver(name='itextpdf', root='http://maven.itextpdf.com/')


import org.springframework.dao.DataIntegrityViolationException
//para crear el archivo
import java.io.FileOutputStream
import java.io.IOException
 
//librería itextpdf para crear el documento PDF
import com.itextpdf.text.pdf.*
import com.itextpdf.text.Document
import com.itextpdf.text.DocumentException
import com.itextpdf.text.Paragraph
//import com.itextpdf.text.pdf.PdfWrite

class CompraController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    def total=0
    def max=0
    def index() {
        redirect(action: "create", params: params)
    }
    //@Grapes(@Grab(group='com.itextpdf', module='itextpdf', version='5.4.1'))
    def pdf(){
        def fichero = new File("C:/fichero.txt")
        
        
        def lista=Compra.list();
        
        try {
           ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Document doc=new Document();
            PdfWriter.getInstance(doc, baos);
            doc.open();
            doc.add(new Paragraph("Nombre:${params.nombre} , Dirección:${params.direccion}"));
            doc.add(new Paragraph(" "));
            PdfPTable table = new PdfPTable(3)
            table.addCell(new Paragraph("Tipo de madera"))
            table.addCell(new Paragraph("Catidad")) 
            table.addCell(new Paragraph("Precio total"))
            lista.each() {
                table.addCell(new Paragraph(it.tipo))
                table.addCell(new Paragraph(it.cantidad.toString())) 
                table.addCell(new Paragraph(it.precio.toString()))
            }
            doc.add(table);
            doc.add(new Paragraph("Maximo Tiempo: ${params.max.toString()} , Total: ${params.Total.toString()}"))
            
            doc.close();
            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close()
            
        } catch (Exception ex) {
            println(ex);
        }
        
    }
    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [compraInstanceList: Compra.list(params), compraInstanceTotal: Compra.count()]
    }

    def create() {
        [compraInstance: new Compra(params),compraInstanceList: Compra.list(params)]
    }

    def save() {
        params.cantidad=new BigDecimal(params.cantidad.replace(".","."))
        def precios=["Cherry":5.95f,"Curly Maple":6.00f,"Genuine Mahogany":9.60f,"Wenge":22.35f,"White Oak":6.70f,"Sawdust":1.5f]
        params['precio']=precios[params.tipo]*params.cantidad
        println(params.cantidad.class)
        println(precios["Cherry"].class)
        def compraInstance = new Compra(params)
        if (!compraInstance.save(flush: true)) {
            render(view: "create", model: [compraInstance: compraInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'compra.label', default: 'Compra'), compraInstance.id])
        redirect(action: "create"/*, id: compraInstance.id*/)
    }

    def show(Long id) {
        def lista=Compra.list();
        def Tiempos=["Cherry":0.5f,"Curly Maple":1.5f,"Genuine Mahogany":3.0f,"Wenge":5.0f,"White Oak":0.0f,"Sawdust":0.0f]
        def maximo=[]
        lista.each {
            def mult=1
            if(it.cantidad>=501) mult=5.5
            else if(it.cantidad>=401) mult=5
            else if(it.cantidad>=301) mult=4
            else if(it.cantidad>=201) mult=3
            else if(it.cantidad>=101) mult=2
            maximo.add(mult*Tiempos[it.tipo])
            total=total+it.precio;
        }
        max=maximo.max()
        [compraInstanceList: Compra.list(),max:max,Total:total]
        //renderPdf( template: "show.gsp", model:[compraInstanceList: Compra.list()], filename: 'doc.pdf')
    
    }

    def edit(Long id) {
        def compraInstance = Compra.get(id)
        if (!compraInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'compra.label', default: 'Compra'), id])
            redirect(action: "list")
            return
        }

        [compraInstance: compraInstance]
    }

    def update(Long id, Long version) {
        def compraInstance = Compra.get(id)
        if (!compraInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'compra.label', default: 'Compra'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (compraInstance.version > version) {
                compraInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'compra.label', default: 'Compra')] as Object[],
                          "Another user has updated this Compra while you were editing")
                render(view: "edit", model: [compraInstance: compraInstance])
                return
            }
        }

        compraInstance.properties = params

        if (!compraInstance.save(flush: true)) {
            render(view: "edit", model: [compraInstance: compraInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'compra.label', default: 'Compra'), compraInstance.id])
        redirect(action: "show", id: compraInstance.id)
    }

    def delete(Long id) {
        def compraInstance = Compra.get(id)
        if (!compraInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'compra.label', default: 'Compra'), id])
            redirect(action: "list")
            return
        }

        try {
            compraInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'compra.label', default: 'Compra'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'compra.label', default: 'Compra'), id])
            redirect(action: "show", id: id)
        }
    }
}
